package com.gitee.yannzh.rune.common.util;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;

import java.lang.reflect.Type;

/**
 * @author: yann
 * @description: json工具类
 * @date: 2024-01-30
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtil {
    @Getter
    private static final ObjectMapper mapper = SpringUtil.getBean(ObjectMapper.class);

    /**
     * 对象转JSON字符串
     *
     * @param object
     * @param mapper
     * @return
     */
    public static String toJSONString(Object object, @NonNull ObjectMapper mapper) {
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(String.format("JSON序列化失败,对象：%s", object), e);
        }
    }


    /**
     * 对象转JSON字符串
     *
     * @param object
     * @return
     */
    public static String toJSONString(Object object) {
        try {
            return getMapper().writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(String.format("JSON序列化失败,对象：%s", object), e);
        }
    }


    /**
     * JSON字符串转对象
     *
     * @param str
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T toJavaObject(String str, Type type) {
        try {
            return mapper.readValue(str, new TypeReference<T>() {
                @Override
                public Type getType() {
                    return type;
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(String.format("JSON反序列化失败,Clazz：%s;JSON:%s", type, str), e);
        }
    }

    /**
     * json字符串
     *
     * @param str
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T toJavaObject(String str, TypeReference<T> type) {
        return toJavaObject(str, type.getType());
    }


}
